package com.nike.amoeba.ui.frg

import android.os.Bundle
import android.os.Handler
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.kingja.loadsir.core.LoadService
import com.nike.amoeba.R
import com.nike.amoeba.base.BaseFragment
import com.nike.amoeba.bean.AppRoomDataBase
import com.nike.amoeba.databinding.FDownloadBinding
import com.nike.amoeba.ext.loadServiceInit
import com.nike.amoeba.ext.showEmpty
import com.nike.amoeba.ext.showLoading
import com.nike.amoeba.mar.eventViewModel
import com.nike.amoeba.util.CacheUtil
import com.nike.amoeba.viewmodel.DownloadModel
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

import java.text.NumberFormat
import java.util.concurrent.TimeUnit


/**
 * @Author nike
 * @Date 2023/7/7 16:51
 * @Description  下载
 */
class DownloadFrg : BaseFragment<DownloadModel, FDownloadBinding>() {

    //界面状态管理者
    lateinit var loadsir: LoadService<Any>

    var assetDisposable: Disposable? = null

    var stockDisposable: Disposable? = null

    val numberFormat = NumberFormat.getInstance()

    var warehouseNumber: Int = 0

    var warehousePageSize: Int = 0

    var assetNumber: Int = 0

    var assetPageSize: Int = 0

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        //状态页配置
        /*loadsir = loadServiceInit(mDatabind.layout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.onWarehouse()
        }*/
        numberFormat.setMaximumFractionDigits(2)

        mDatabind.pvAsset.setOnProgressChangeListener{
            mDatabind.pvAsset.labelText = "$assetNumber" + "/" + "$assetPageSize" + " " + "${it.toInt()}%"
        }

        mDatabind.pvStock.setOnProgressChangeListener{
            mDatabind.pvStock.labelText = "$warehouseNumber" + "/" + "$warehousePageSize" + " " + "${it.toInt()}%"
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                assetDisposable?.dispose()
                stockDisposable?.dispose()
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                assetDisposable?.dispose()
                stockDisposable?.dispose()
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                mViewModel.viewModelScope.launch(Dispatchers.IO) {
                    mViewModel.existEpcDao.deleteById(mViewModel.userId!!, mViewModel.companyId!!)
                    mViewModel.taskStockListDao.deleteById(mViewModel.userId!!, mViewModel.companyId!!)
                    mViewModel.taskStockDao.deleteById(mViewModel.userId!!, mViewModel.companyId!!)
                    mViewModel.stockEpcDao.deleteAll()

                    mViewModel.taskAssetDao.deleteById(mViewModel.userId!!!!, mViewModel.companyId!!!!)
                    mViewModel.assetDao.deleteById(mViewModel.userId!!, mViewModel.companyId!!)

                    mViewModel.uploadOrderDao.deleteById(mViewModel.userId!!, mViewModel.companyId!!)
                    mViewModel.uploadOrderListDao.deleteById(mViewModel.userId!!, mViewModel.companyId!!)

                    withContext(Dispatchers.Main) {
                        mDatabind.pvStock.progress = 0f
                        mDatabind.pvAsset.progress = 0f
//                eventViewModel.mainListEvent.postValue(true)
                        //旧的下载
                        mViewModel.onRequest()
                        mViewModel.onWarehouse()
                        //新模组化下载
//                mViewModel.onModuleList()
                    }
                }
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listAssetBean.observe(viewLifecycleOwner, Observer {
            if (it.pageSize != 0) {
                assetPageSize = it.pageSize
                mViewModel.viewModelScope.launch {
                    /*mViewModel.assetDao.findAll(mViewModel.userId!!, mViewModel.companyId!!)
                        .flowOn(Dispatchers.IO)
                        .collect { data ->
                            assetNumber = data.size
                        }*/
                }

                assetDisposable = Observable.interval(1, TimeUnit.SECONDS)
                    .observeOn(Schedulers.io()) // 切换到IO线程执行操作
                    .doOnDispose {

                    }
                    .subscribe ({ tick ->
                        var result = numberFormat.format(assetNumber.toFloat() / assetPageSize.toFloat() * 100).toFloat()
                        mDatabind.pvAsset.progress = result
                        LogUtils.i(assetNumber, result)

                        if (assetNumber >= it.pageSize){
                            assetDisposable?.dispose()
//                            eventViewModel.assetListUploadEvent.postValue(true)
                        }
                    }, { error ->
                        // Handle the error here
                        LogUtils.e(error)
                    })
            }
        })

        mViewModel.listStockBean.observe(viewLifecycleOwner, Observer {
            if (it.isSuccess) {
                if (it.pageSize != 0) {
                    warehousePageSize = it.pageSize
                    /*mViewModel.viewModelScope.launch {
                        mViewModel.taskStockListDao.findAll(mViewModel.userId!!, mViewModel.companyId!!, "")
                            .flowOn(Dispatchers.IO)
                            .collect { data ->
                                warehouseNumber = data.size
                            }
                        *//*existEpcDao.findAll(roNo, companyID)
                            .flowOn(Dispatchers.IO)
                            .collect { data ->
                                number = data.size
                            }*//*
                    }*/

                    stockDisposable = Observable.interval(1, TimeUnit.SECONDS)
                        .observeOn(Schedulers.io()) // 切换到IO线程执行操作
                        .doOnDispose {

                        }
                        .subscribe ({ tick ->
                            var result = numberFormat.format(warehouseNumber.toFloat() / warehousePageSize.toFloat() * 100).toFloat()
                            mDatabind.pvStock.progress = result
                            LogUtils.i(warehouseNumber, result)

                            if (warehouseNumber >= it.pageSize){
                                stockDisposable?.dispose()
//                                eventViewModel.stockListUploadEvent.postValue(true)
                            }
                        }, { error ->
                            // Handle the error here
                            LogUtils.e(error)
                        })
                }
            }
        })
    }

}